<template>
    <div class="container" :style="userSetting">
        <div class="option">
            <el-icon @click="changeView(1)">
                <HomeFilled />
            </el-icon>
            <el-icon @click="changeView(2)">
                <Search />
            </el-icon>
            <el-icon @click="changeView(3)">
                <Reading />
            </el-icon>
            <el-icon v-if="viewNum == 1" @click="() => { isShow = true }">
                <CirclePlusFilled />
            </el-icon>
            <el-icon v-if="viewNum == 3" @click="() => { isShowSetting = true }">
                <Tools />
            </el-icon>
            <el-icon v-if="viewNum == 3" @click="readLineType">
                <Position />
            </el-icon>
            <el-icon v-if="viewNum == 3" @click="updateCurrentBook(lastRead.current - 1)">
                <ArrowLeftBold />
            </el-icon>
            <el-icon v-if="viewNum == 3" @click="updateCurrentBook(lastRead.current + 1)">
                <ArrowRightBold />
            </el-icon>
            <el-icon v-if="!isInBookList()" @click="starBook">
                <Star />
            </el-icon>
            <el-icon v-if="viewNum == 3 && isInBookList()" @click="deleteBook">
                <DeleteFilled />
            </el-icon>
            <el-icon v-if="viewNum == 3" @click="speak(sectionData.sectionContent)">
                <Microphone />
            </el-icon>
            <el-icon v-if="viewNum == 3" @click="stop">
                <Mute />
            </el-icon>
        </div>
        <div class="pageBox" v-if="viewNum == 3">
            {{ lastRead?.current + 1 || 0 }} / {{ lastRead?.total || 0 }}
        </div>
        <div class="main" v-if="viewNum == 1">
            <el-row :gutter="20" v-for="item in Math.ceil(booksList.length / 3)">
                <el-col :span="8" v-for="ele in booksList.slice((item - 1) * 3, item * 3)">
                    <el-card @click="changeView(3, ele)">
                        <div>{{ ele.name }}</div>
                    </el-card>
                </el-col>
            </el-row>
        </div>
        <div class="main" v-if="viewNum === 2">
            <!-- 按下enter事件 -->
            <el-input v-model="searchBookName" style="width: 240px" placeholder="输入书名" clearable :prefix-icon="Search"
                @keyup.enter.native="searchBook" />
            <div class="searchRes">
                <div class="resItem" v-for="(item, index) in bookSearchRes" :key="index">
                    <!-- <img :src="item.imgUrl" :alt="item.title"> -->
                    <div class="itemTitle"
                        @click="changeView(3, { name: item.title, author: item.author, type: 'online', current: 0, total: 0, webUrl: item.txtUrl })">
                        {{ item.title + "---" + item.author }}</div>
                </div>
            </div>
        </div>
        <div class="main" v-if="viewNum === 3">
            <p class="title">{{ sectionData.sectionName }}</p>
            <div class="content">{{ sectionData.sectionContent }}</div>
        </div>
        <el-drawer v-model="isShow" direction="btt" :with-header="false">
            <template #default>
                <el-form :model="form" size="small" label-width="auto" style="max-width: 600px">
                    <el-form-item label="Name">
                        <el-input v-model="form.name" />
                    </el-form-item>
                    <el-form-item label="File">
                        <input type="file" name="file" id="file" @change="fileChange">
                    </el-form-item>
                    <el-form-item label="Url">
                        <el-input v-model="form.localUrl" />
                    </el-form-item>
                </el-form>
                <div style="width: 100%; text-align: right">
                    <el-button size="small" type="primary" @click="confirmClick">confirm</el-button>
                </div>
            </template>
        </el-drawer>
        <el-drawer v-model="isShowSetting" direction="ttb" :with-header="false">
            <template #default>
                <el-form :model="form1" size="small" label-width="auto" style="max-width: 600px">
                    <div class="line">
                        <el-form-item label="开启背景">
                            <el-switch v-model="form1.isShowBg" />
                        </el-form-item>
                        <el-form-item label="开启边框">
                            <el-switch v-model="form1.isShowBd" />
                        </el-form-item>
                    </div>
                    <div class="line">
                        <el-form-item label="文字颜色">
                            <el-color-picker v-model="form1.color" show-alpha size="default" :teleported="false" />
                        </el-form-item>
                        <el-form-item label="背景颜色">
                            <el-color-picker v-model="form1.background" show-alpha size="default" :teleported="false" />
                        </el-form-item>
                        <el-form-item label="边框颜色">
                            <el-color-picker v-model="form1.borderColor" show-alpha size="default"
                                :teleported="false" />
                        </el-form-item>
                    </div>
                    <el-form-item label="字体大小">
                        <el-input-number v-model="form1.fontSize" />
                    </el-form-item>
                    <el-form-item label="行高">
                        <el-input-number v-model="form1.lineHeight" />
                    </el-form-item>
                    <el-form-item label="语速">
                        <input type="range" id="rate" v-model.number="rate" min="0.5" max="2" step="0.1">
                    </el-form-item>
                    <el-form-item label="音量">
                        <input type="range" id="volume" v-model.number="volume" min="0" max="1" step="0.1">
                    </el-form-item>
                </el-form>
                <el-form-item>
                    <el-button type="warning" style="width: 100%;" @click="remenber">记录当前位置和大小</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" style="width: 100%;" @click="onSubmit">保存</el-button>
                </el-form-item>
                <div style="width: 100%;font-size: 12px;text-align: center;color: #999">❗选择颜色记得点“ok”</div>

            </template>
        </el-drawer>
    </div>
</template>
<script setup>
import { HomeFilled, Search, Tools, ArrowLeftBold, ArrowRightBold, CirclePlusFilled, Reading, Star, DeleteFilled, Position,Microphone,Mute } from '@element-plus/icons-vue';
import { ref, onMounted, watch } from 'vue';

const viewNum = ref(1) // 1:首页 2:搜索 3:阅读
const isShow = ref(false)
const isShowSetting = ref(false)
const form = ref({})
const form1 = ref({})
const booksList = ref([])
const lastRead = ref({})
const userSetting = ref({
})
const sectionData = ref({})
const searchBookName = ref('')
const bookSearchRes = ref([])
// 发言实例
const utterance = ref(null);
const voices = ref([]);
const selectedVoice = ref(null);
const rate = ref(1.5);
const volume = ref(1);
const isSpeaking = ref(false);
const loadVoices = () => {
    voices.value = speechSynthesis.getVoices();
    if (voices.value.length > 0) {
        selectedVoice.value = voices.value[0];
    }
};

const speak = (text) => {
    isSpeaking.value = true;
    if (utterance.value) {
        speechSynthesis.cancel();
    }
    utterance.value = new SpeechSynthesisUtterance(text);
    utterance.value.voice = selectedVoice.value;
    utterance.value.rate = rate.value;
    utterance.value.volume = volume.value;

    // 监听语音合成结束事件
    utterance.value.onend = () => {
        // 朗读"本章结束，等待下一章内容"
        const endText = "本章结束，等待下一章内容";
        const endUtterance = new SpeechSynthesisUtterance(endText);
        endUtterance.voice = selectedVoice.value;
        endUtterance.rate = rate.value;
        endUtterance.volume = volume.value;

        endUtterance.onend = () => {
            // 切换到下一章
            updateCurrentBook(lastRead.value.current + 1);
        };

        speechSynthesis.speak(endUtterance);
    };

    speechSynthesis.speak(utterance.value);
};
const stop = () => {
    isSpeaking.value = false;
    if (utterance.value) {
        speechSynthesis.cancel();
    }
};
onMounted(() => {
    loadVoices()
    if (speechSynthesis.onvoiceschanged !== undefined) {
        speechSynthesis.onvoiceschanged = loadVoices;
    }
    window.electron.ipcRenderer.send('getBooks', JSON.stringify({}));
    window.electron.ipcRenderer.on('books', init);
    window.electron.ipcRenderer.on('section', initSection);
    window.electron.ipcRenderer.on('updated', () => {
        window.electron.ipcRenderer.send('getSection', JSON.stringify({}));
    });
    window.electron.ipcRenderer.on('returnSearchResult', initSearch);
    // 绑定方向键切换章节
    document.addEventListener('keydown', function (event) {
        let h = Number(userSetting.value.lineHeight.replace('px', ''))
        if ((event.key === 'ArrowRight' || event.key === 'd') && viewNum.value == 3) {
            updateCurrentBook(lastRead.value.current + 1)
        }
        if ((event.key === 'ArrowLeft' || event.key === 'a') && viewNum.value == 3) {
            updateCurrentBook(lastRead.value.current - 1)
        }
        if ((event.key === 'ArrowDown' || event.key === 's') && viewNum.value == 3) {
            document.querySelector('.main').scrollBy(0, h)
        }
        if ((event.key === 'ArrowUp' || event.key === 'w') && viewNum.value == 3) {
            document.querySelector('.main').scrollBy(0, -h);
        }
    });
    window.electron.ipcRenderer.on('returnRemenber', (event, data) => {
        userSetting.value.Bounds = JSON.parse(data)
    });
    window.electron.ipcRenderer.on('startReadBook', (event, data) => {
        speak(sectionData.value.sectionContent)
    });
    window.electron.ipcRenderer.on('stopReadBook', (event, data) => {
        stop()
    });
});
const init = (event, data) => {
    booksList.value = JSON.parse(data).booksList
    lastRead.value = JSON.parse(data).lastRead == null ? {} : JSON.parse(data).lastRead
    userSetting.value = JSON.parse(data).userSetting
    if (JSON.parse(data).lastRead != null && Object.keys(JSON.parse(data).lastRead).length > 0) {
        viewNum.value = 3
    }
    form1.value = {
        color: userSetting.value.color,
        background: userSetting.value.background == 'none' ? undefined : userSetting.value.background,
        borderColor: userSetting.value.border != 'none' ? userSetting.value.border.replace('1px solid', '') : undefined,
        fontSize: Number(userSetting.value.fontSize.replace('px', '')),
        isShowBg: userSetting.value.background == 'none' ? false : true,
        isShowBd: userSetting.value.border != 'none' ? true : false,
        lineHeight: Number(userSetting.value.lineHeight.replace('px', '')),
    }
}
const initSection = (event, data) => {
    if (data == '无') {
        sectionData.value = {
            sectionContent: '无',
            sectionName: '无'
        }
    } else {
        sectionData.value = JSON.parse(data)
        // sectionData.value.sectionContent = sectionData.value.sectionContent.slice(0, 100) + '...'
        if (isSpeaking.value) {
            speak(sectionData.value.sectionContent)
        }
        updateCurrentBook()
    }
    lastRead.value.total = sectionData.value.total

}
const initSearch = (event, data) => {
    let res = JSON.parse(data)
    const parser = new DOMParser()
    const doc = parser.parseFromString(res.text, 'text/html')
    const nodes = doc.body
    let array = nodes.querySelectorAll(".tutui")
    bookSearchRes.value = []
    array.forEach((ele, i) => {
        let obj = {
            imgUrl: ele.querySelector(".tutuiImg a img").src,
            title: ele.querySelector('.tutuiTitle h2 a').innerHTML,
            author: ele.querySelector('.tutuiTitle h3').innerHTML,
            txtUrl: ele.querySelector('.tutuiTitle h2 a').href
        }
        bookSearchRes.value.push(obj)
    })
}

const updateCurrentBook = (index) => {
    if (index >= 0) {
        if (index > lastRead.value.total - 1) {
            index = lastRead.value.total - 1
        }
        lastRead.value.current = index
        let ele = document.querySelector('.main')
        ele.scrollTo(0, 0)
    }
    booksList.value.forEach((item, index) => {
        if (item.name == lastRead.value.name) {
            booksList.value[index].current = lastRead.value.current
            booksList.value[index].total = lastRead.value.total
        }
    })
}
const readLineType = () => {
    window.electron.ipcRenderer.send('rememberType', 'true');
}
const changeView = (num, ele) => {
    viewNum.value = num
    if (num == 3) {
        if (ele) {
            lastRead.value = {
                ...ele
            }
        }
        window.electron.ipcRenderer.send('getSection', JSON.stringify({}));
    }
}
const fileChange = (e) => {
    let file = e.target.files[0]
    form.value.name = file.name.split('.')[0]
    form.value.localUrl = file.path
}
const confirmClick = () => {
    booksList.value.push({
        ...form.value,
        type: 'offline',
        current: 0,
        total: 0
    })
    console.log('booksList', booksList.value);
    isShow.value = false
}
const onSubmit = () => {
    if (!form1.value.isShowBg) {
        form1.value.background = 'none'
    }
    if (!form1.value.isShowBd) {
        form1.value.border = 'none'
    } else {
        form1.value.border = `1px solid ${form1.value.borderColor}`;
    }
    userSetting.value = {
        color: form1.value.color,
        fontSize: form1.value.fontSize + 'px',
        background: form1.value.background,
        border: form1.value.border,
        lineHeight: form1.value.lineHeight + 'px',
    }
    isShowSetting.value = false
}
// 记录
const remenber = () => {
    window.electron.ipcRenderer.send('remenber', Date.now());
    isShowSetting.value = false
}
const searchBook = () => {
    window.electron.ipcRenderer.send('searchBook', searchBookName.value);
}
const isInBookList = () => {
    let book = booksList.value.find(item => item.name == lastRead.value.name)
    if (book) {
        return true
    }
    return false
}
const starBook = () => {
    booksList.value.push({
        ...lastRead.value,
    })
}
const deleteBook = () => {
    booksList.value = booksList.value.filter(item => item.name != lastRead.value.name)
    changeView(1)
}
// 监听booksList的变化
watch(booksList, (newVal, oldVal) => {
    window.electron.ipcRenderer.send('setBooks', JSON.stringify({
        booksList: newVal,
        lastRead: lastRead.value,
        userSetting: userSetting.value
    }));
}, { deep: true });
// 监听lastRead的变化
watch(lastRead, (newVal, oldVal) => {
    window.electron.ipcRenderer.send('setBooks', JSON.stringify({
        booksList: booksList.value,
        lastRead: newVal,
        userSetting: userSetting.value
    }));
}, { deep: true });
// 监听userSetting的变化
watch(userSetting, (newVal, oldVal) => {
    window.electron.ipcRenderer.send('setBooks', JSON.stringify({
        booksList: booksList.value,
        lastRead: lastRead.value,
        userSetting: newVal,
    }));
}, { deep: true });

</script>
<style lang="less" scoped>
.container {
    width: 100vw;
    height: 100vh;
    padding: 10px;
    position: relative;
    border-radius: 10px;
    overflow: hidden;
    border: 1px solid #333;
    color: #333;
    opacity: 0.9;

    .line {
        display: flex;
        justify-content: flex-start;
        align-items: center;
    }

    :deep(.el-drawer) {
        height: 75% !important;
        color: #333;

        .el-drawer__body {
            padding: 10px 5px;
            scrollbar-width: none;
            /* Firefox */
            -ms-overflow-style: none;
            /* IE 10+ */

            &::-webkit-scrollbar {
                display: none;
            }
        }

        .line {
            display: flex;
            justify-content: space-around;
            align-items: center;
        }
    }

    .pageBox {
        position: absolute;
        bottom: 0;
        right: 10px;
        line-height: 32px;
        font-size: 15px;
        color: #333;
    }

    .option {
        font-size: 16px;
        height: 18px;
        position: absolute;
        bottom: 0;
        left: 5px;
        z-index: 999;
        background: none;
        -webkit-app-region: no-drag;

        .el-icon {
            cursor: pointer;
            transition: 0.3s;
            color: #CDD0D6;
            margin-right: 5px;
            border-radius: 50%;

            &:hover {
                color: #303133;
            }
        }

    }

    .main {
        width: 100%;
        height: 92%;
        -webkit-app-region: no-drag;
        overflow-y: scroll;
        scrollbar-width: none;
        /* Firefox */
        -ms-overflow-style: none;
        /* IE 10+ */

        &::-webkit-scrollbar {
            display: none;
        }

        .el-input {
            width: 100% !important;

            :deep(.el-input__wrapper) {
                background: none !important;
                color: #333 !important;

                .el-input__prefix {
                    color: #333;
                }
            }
        }

        .searchRes {
            display: flex;
            flex-direction: column;
            width: 100%;

            .resItem {
                width: 100%;
                height: 30px;
                margin-top: 5px;
                font-size: 13px;
                display: flex;

                .itemTitle {
                    // 单行超出省略
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                    width: 100%;
                    height: 100%;
                    padding: 0 5px;
                    line-height: 30px;
                    cursor: pointer;
                    border: 1px solid #333;
                    border-radius: 5px;
                    transition: .3s;

                    &:hover {
                        background-color: #333;
                        color: #fff;
                    }
                }
            }
        }

        .title {
            font-size: 12px;
        }

        .el-row {
            margin-bottom: 20px;
        }

        .el-card {
            font-size: 12px;
            font-weight: bold;
            cursor: pointer;
            background-color: #333;
            color: #fff;

            // 单行超出省略
            :deep(.el-card__body) {
                width: 100%;
                height: 100%;
                padding: 0;

                div {
                    padding: 20px 5px;
                    width: 100%;
                    height: 100%;
                    text-align: center;
                    overflow: hidden;
                    text-overflow: ellipsis;
                    white-space: nowrap;
                }

            }


            &:hover {
                background-color: #fff;
                color: #333;
                border: 1px solid #333;
                transition: 0.3s;
            }
        }
    }
}
</style>